package org.neogenesis.web.dao;

import java.io.Serializable;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;

import org.neogenesis.web.model.Organism;
import org.neogenesis.web.qualifier.DataRepository;

@SessionScoped
@Default
public class OrganismDAO implements Serializable {

	@Inject
	@DataRepository
	private EntityManager em;

	public OrganismDAO() {
		// TODO Auto-generated constructor stub
	}

	public void create(Organism organism) {
		EntityTransaction et = em.getTransaction();
		et.begin();
		em.persist(organism);
		et.commit();
	}

	public void edit(Organism organism) {
		em.merge(organism);
	}

	public void remove(Organism organism) {
		em.remove(em.merge(organism));
	}

	public Organism find(Object id) {
		return em.find(Organism.class, id);
	}

	public List<Organism> findAll() {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(Organism.class));
		return em.createQuery(cq).getResultList();
	}

	public List<Organism> findRange(int[] range) {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(Organism.class));
		javax.persistence.Query q = em.createQuery(cq);
		q.setMaxResults(range[1] - range[0]);
		q.setFirstResult(range[0]);
		return q.getResultList();
	}

	public int count() {
		javax.persistence.criteria.CriteriaQuery cq = em.getCriteriaBuilder()
				.createQuery();
		javax.persistence.criteria.Root<Organism> rt = cq.from(Organism.class);
		cq.select(em.getCriteriaBuilder().count(rt));
		javax.persistence.Query q = em.createQuery(cq);
		return ((Long) q.getSingleResult()).intValue();
	}

	public Organism findByName(String name) {
		Query query = em
				.createQuery("SELECT o FROM Organism o WHERE o.name = :name",
						Organism.class);
		query.setParameter("name", name);

		List<Organism> organisms = query.getResultList();

		if (organisms.size() > 0)
			return organisms.get(0);

		return null;
	}
}
